
/*
	pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.

	This file is part of pbrt.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are
	met:

	- Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.

	- Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
	IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
	TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
	PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
	HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
	DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
	THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
	OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	*/

#if defined(_MSC_VER)
#pragma once
#endif

#ifndef PBRT_RENDERERS_METROPOLIS_H
#define PBRT_RENDERERS_METROPOLIS_H

// renderers/metropolis.h*
#include "pbrt.h"
#include "renderer.h"
#include "parallel.h"
#include "renderers/samplerrenderer.h"
#include "scene.h"
#include "imageio.h"
#include "spectrum.h"
#include "camera.h"
#include "film.h"
#include "rng.h"
#include "progressreporter.h"
#include "paramset.h"
#include "probes.h"
#include "intersection.h"
#include "montecarlo.h"
#include "samplers/lowdiscrepancy.h"
#include "integrators/directlighting.h"
#include "integrators/path.h"


struct PathSample {
	BSDFSample bsdfSample;
	float rrSample;
};


struct LightingSample {
	BSDFSample bsdfSample;
	float lightNum;
	LightSample lightSample;
};


struct MLTSample {
	MLTSample(int maxLength);

	CameraSample cameraSample;
	float lightNumSample, lightRaySamples[5];
	vector<PathSample> cameraPathSamples, lightPathSamples;
	vector<LightingSample> lightingSamples;
};


struct MLTRenderData {
	MLTRenderData(MemoryArena &arena, RNG &rng,
	PathVertex *cameraPath = NULL, PathVertex* lightPath = NULL, 
	int cameraPathLength = 0, int lightPathLength = 0);

	RayDifferential escapedRay;
	Spectrum escapedAlpha;
	PathVertex *cameraPath, *lightPath;
	int cameraPathLength, lightPathLength;

	MemoryArena &arena;
	RNG &rng;
};


class MetropolisRenderer : public Renderer {
public:
	MetropolisRenderer(int perPixelSamples, int nBootstrap, 
		int directPixelSamples, float largeStepProbability, 
		bool doDirectSeparately, int maxConsecutiveRejects, int maxDepth, 
		Camera *camera, bool doBidirectional);
	~MetropolisRenderer();

	void Render(const Scene *scene);
	IntegrationResult Li(const Scene *scene, const RayDifferential &ray,
		const Sample *sample, RNG &rng, MemoryArena &arena,
		Intersection *isect = NULL, Spectrum *T = NULL) const;
	Spectrum Transmittance(const Scene *scene, const RayDifferential &ray,
		const Sample *sample, RNG &rng, MemoryArena &arena) const;

protected:
	void LaunchDirectTasks();
	void LaunchMLTTasks(MLTRenderData &data, MLTSample &initialSample, float b);
	float Bootstrap(MLTRenderData &data, float *sumI, vector<float> *bootstrapI);
	MLTSample GetInitialSample(MLTRenderData &data, float sumI, float *bootstrapI);

	Spectrum PathL(MLTRenderData &data, MLTSample &sample) const;
	float GenerateCameraRay(const MLTSample &sample, RayDifferential *ray) const;
	Spectrum SampleLightBidir(MLTRenderData &data, MLTSample &sample, 
		float *lightRayPdf, Ray *lightRay) const;

	Spectrum Lpath(MLTRenderData &data, MLTSample &sample) const;
	Spectrum DirectLightingVertex(MLTRenderData &data, MLTSample &sample, 
		int pathIdx, const PathVertex &vc, const Point &pc, 
		const Normal &nc) const;
	Spectrum EscapedRayL(MLTRenderData &data, bool prevSpecular, 
		bool allSpecular) const;

	Spectrum Lbidir(MLTRenderData &data, MLTSample &sample) const;
	void GetNumSpecularVertices(MLTRenderData &data, int *nSpecularVertices) const;
	Spectrum LightPathL(MLTRenderData &data, MLTSample &sample, const Point &pc, 
		const PathVertex &vc, const Normal &nc, int *nSpecularVertices, 
		int cameraPathIdx, int lightPathIdx) const;

	void LargeStep(MLTRenderData &data, MLTSample *sample, float x, float y) const;
	void mutate(RNG &rng, float *v, float min = 0.f, float max = 1.f) const;
	void SmallStep(MLTRenderData &data, MLTSample *sample) const;

	uint32_t GeneratePath(MLTRenderData &data, MLTSample &sample, 
		const RayDifferential &r, const Spectrum &a, bool isLightPath) const;
	bool GeneratePathVertex(MLTRenderData &data, RayDifferential &ray,
		Spectrum &alpha, bool isLightPath, PathVertex *v) const;
	bool RussianRoulette(PathVertex &v, Spectrum &f, float pdf, float rrSample, 
		RayDifferential *ray, Spectrum *alpha) const;

	inline float calcI(const Spectrum &L) { return L.y(); }

	Camera *camera;
	const Scene *scene;
	Distribution1D *lightDistribution;
	bool bidirectional;
	uint32_t nDirectPixelSamples, nPixelSamples, maxDepth;
	uint32_t largeStepsPerPixel, nBootstrap, maxConsecutiveRejects;
	DirectLightingIntegrator *directLightingIntegrator;
	AtomicInt32 nTasksFinished;
	friend class MLTTask;
};


MetropolisRenderer *CreateMetropolisRenderer(const ParamSet &params,
	Camera *camera);

class MLTTask : public Task {
public:
	MLTTask(ProgressReporter &prog, uint32_t pfreq, uint32_t taskNum,
		float dx, float dy, int xx0, int xx1, int yy0, int yy1, float tt0, 
		float tt1, float bb, const MLTSample &is, MetropolisRenderer *renderer,
		Mutex *filmMutex);
	void Run();

protected:
	void Init(MLTRenderData &data, MLTSample *samples, Spectrum *L, float *I);
	void Mutate(MLTRenderData &data, uint64_t sampleIdx, MLTSample *sample);
	void SplatSample(float acceptProb, MLTSample *samples, Spectrum *L, float *I);
	void VetMutation(MLTRenderData &data, float acceptProb);
	void UpdateDisplay();

	// Inherited from renderer
	ProgressReporter &progress;
	uint32_t progressUpdateFrequency, taskNum;
	float dx, dy;
	int currentPixelSample;
	int x0, x1, y0, y1;
	float t0, t1;
	float b;
	const MLTSample &initialSample;
	MetropolisRenderer *renderer;
	Mutex *filmMutex;
	
	// Defined internally
	uint32_t nPixels;
	uint32_t nPixelSamples;
	uint32_t largeStepRate;
	uint64_t nTaskSamples;
	uint32_t consecutiveRejects;
	uint32_t progressCounter;
	uint32_t current, proposed;
	uint32_t pixelNumOffset;
	vector<int> largeStepPixelNum;
};

#endif // PBRT_RENDERERS_METROPOLIS_H
